package com.zzyl.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.service.impl.handler.FristResourceFilterHandler;
import com.zzyl.service.impl.handler.SecondResourceFilterHandler;
import com.zzyl.service.impl.handler.ThirdResourceFilterHandler;
import com.zzyl.utils.*;
import com.zzyl.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;
    /**
     * 根据条件查询资源列表
     * @param resourceDto
     * @return
     */
    @Override
    public List<ResourceVo> list(ResourceDto resourceDto) {
        Resource resource = new Resource();
        BeanUtils.copyProperties(resourceDto,resource);
        if(StringUtils.isNotEmpty(resource.getParentResourceNo())){
            resource.setParentResourceNo(NoProcessing.processString(resource.getParentResourceNo()));
        }
        List<Resource> list = resourceMapper.list(resource);
        return BeanUtil.copyToList(list,ResourceVo.class);
    }

    /**
     * 查询资源层级关系
     *
     * @param resourceDto
     * @return
     */
    @Override
    public TreeVo tree(ResourceDto resourceDto) {
        Resource resource = Resource.builder()
                .resourceNo(NoProcessing.processString(SuperConstant.ROOT_PARENT_ID))
                .resourceType(SuperConstant.MENU)
                .dataState(SuperConstant.DATA_STATE_0)
                .build();
        List<Resource> list = resourceMapper.list(resource);

        TreeItemVo root = new TreeItemVo();
        root.setId("100001000000000");
        root.setLabel("智慧养老院");

        FristResourceFilterHandler h1 = new FristResourceFilterHandler();
        SecondResourceFilterHandler h2 = new SecondResourceFilterHandler();
        ThirdResourceFilterHandler h3 = new ThirdResourceFilterHandler();

        h1.setNextHandler(h2);
        h2.setNextHandler(h3);

        h1.filter(list,root);
//        List<TreeItemVo> first = list.stream().filter(r -> {
//            if (NoProcessing.processString(r.getParentResourceNo()).equals(resource.getResourceNo())) {
//                return true;
//            } else {
//                return false;
//            }
//        }).map(r -> {
//            TreeItemVo vo = new TreeItemVo();
//            vo.setId(r.getResourceNo());
//            vo.setLabel(r.getResourceName());
//            return vo;
//        }).collect(Collectors.toList());
//        root.setChildren(first);
//
//        root.getChildren().stream().map(r -> {
//            List<TreeItemVo> second = list.stream().filter(re -> {
//                if (re.getParentResourceNo().equals(r.getId())) {
//                    return true;
//                } else {
//                    return false;
//                }
//            }).map(re -> {
//                TreeItemVo vo = new TreeItemVo();
//                vo.setId(re.getResourceNo());
//                vo.setLabel(re.getResourceName());
//                return vo;
//            }).collect(Collectors.toList());
//            r.setChildren(second);
//            return r;
//        }).collect(Collectors.toList());
//
//        root.getChildren().stream().map(r ->{
//            r.getChildren().stream().map(m->{
//                List<TreeItemVo> thrid = list.stream().filter(n -> {
//                    if (n.getParentResourceNo().equals(m.getId())) {
//                        return true;
//                    } else {
//                        return false;
//                    }
//                }).map(n -> {
//                    TreeItemVo vo = new TreeItemVo();
//                    vo.setId(n.getResourceNo());
//                    vo.setLabel(n.getResourceName());
//                    return vo;
//                }).collect(Collectors.toList());
//                m.setChildren(thrid);
//                return m;
//            }).collect(Collectors.toList());
//            return r;
//        }).collect(Collectors.toList());

        TreeVo vo = new TreeVo();
        vo.setItems(Arrays.asList(root));

        return vo;
//        if(EmptyUtil.isNullOrEmpty(list)){
//            throw new RuntimeException("资源信息未定义");
//        }
//        //没有根节点，构建根节点
//        Resource rootResource = new Resource();
//        rootResource.setResourceNo(SuperConstant.ROOT_PARENT_ID);
//        rootResource.setResourceName("智慧养老院");
//
//        //返回的树形集合
//        List<TreeItemVo> itemVos = new ArrayList<>();
//
//        //使用递归构建树形结构
//        recursionTreeItem(itemVos,rootResource,list);
//
//        //数据返回
//        return TreeVo.builder().items(itemVos).build();
    }

    /**
     * 资源的添加
     *
     * @param resourceDto
     */
    @Override
    public void createResource(ResourceDto resourceDto) {
        //创建Pojo对象，拷贝数据
        Resource resource = new Resource();
        BeanUtils.copyProperties(resourceDto,resource);
        //查询父菜单状态，给子菜单设置状态
        Resource r = resourceMapper.selectParentStatus(resourceDto.getParentResourceNo());
        resource.setDataState(r.getDataState());
        //设置当前新增状态的编码
        resource.setResourceNo(createResourceNo(resourceDto));
        //补充通用字段
        resource.setCreateBy(1671362878457892866L);
        resource.setCreateTime(LocalDateTime.now());
        resource.setUpdateTime(LocalDateTime.now());
        //保存到数据库
        resourceMapper.insert(resource);
    }

    /**
     * 资源修改
     *
     * @param resourceDto
     */
    @Override
    public void updateResource(ResourceDto resourceDto) {
        //拷贝数据

        //查询父资源编号下的所有数据
        //判断是否有数据，有数据就找出最大子资源编号+1，没有就直接生成编号
        //调用接口修改数据
    }

    @Override
    public List<MenuVo> getMenusById() {
        String json = UserThreadLocal.getSubject();
        UserVo userVo = JSONUtil.toBean(json, UserVo.class);
        List<MenuVo> menusList = resourceMapper.getMenusById(userVo.getId());
        if(ObjectUtil.isEmpty(menusList)){
            throw new BaseException(BasicEnum.USER_ROLE_AND_MENU_EMPTY);
        }
        Map<String, List<MenuVo>> collect = menusList.stream().collect(Collectors.groupingBy(MenuVo::getParentResourceNo));
        menusList.stream().forEach(menuVo -> {
            menuVo.setId(userVo.getId());
            menuVo.setRedirect("/"+menuVo.getName());
            menuVo.setMeta(new MenuMetaVo().builder().title(menuVo.getName()).build());
            collect.keySet().stream().forEach(r->{
                if(menuVo.getResourceNo().equals(r)){
                    menuVo.setChildren(collect.get(r));
                }
            });
//            List<MenuVo> list = collect.get(menuVo.getResourceNo());
//            if(!ObjectUtil.isEmpty(list)){
//                menuVo.setChildren(list);
//            }
        });

        return collect.get(SuperConstant.ROOT_PARENT_ID);
    }

    /**
     * 生成资源编号
     * @param resourceDto
     * @return
     */
    private String createResourceNo(ResourceDto resourceDto) {
        //如果创建的不是按钮，并且层级高于3层，抛出异常
        if(StringUtils.isNotEmpty(resourceDto.getResourceNo()) && !"r".equals(resourceDto.getResourceType())){
            if(NoProcessing.processString(resourceDto.getResourceNo()).length() >12){
                throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
            }
        }
        //查询父资源编号下所有子菜单
        Resource resource = new Resource();
        resource.setParentResourceNo(resourceDto.getParentResourceNo());
        List<Resource> list = resourceMapper.list(resource);

        //判断子菜单是否为空，不存在就在父资源编号的基础上加上001
        if(null == list || list.size() == 0){
            return NoProcessing.createNo(resourceDto.getParentResourceNo(),false);
        }else {
            //如果有子菜单就找到最大的子资源编号，然后+1
            Long maxNo = list.stream().map(r -> Long.parseLong(r.getResourceNo())).max(Comparator.comparing(i -> i)).get();
            return NoProcessing.createNo(maxNo.toString(),true);
        }
    }

    //参数：返回的结果集合，根节点，所有数据
    private void recursionTreeItem(List<TreeItemVo> itemVos, Resource rootResource, List<Resource> resourceList) {
        //构建每个资源的属性
        TreeItemVo treeItemVo = TreeItemVo.builder()
                .id(rootResource.getResourceNo())
                .label(rootResource.getResourceName()).build();

        //获取当前资源下子资源
        List<Resource> childrenResourceList = resourceList.stream()
                .filter(n -> n.getParentResourceNo().equals(rootResource.getResourceNo()))
                .collect(Collectors.toList());
        //判断子资源是否为空
        if(!EmptyUtil.isNullOrEmpty(childrenResourceList)){

            List<TreeItemVo> listChildren = new ArrayList<>();
            //构建子资源
            childrenResourceList.forEach(resource -> {
                recursionTreeItem(listChildren,resource,resourceList);
            });
            treeItemVo.setChildren(listChildren);
        }

        itemVos.add(treeItemVo);
    }
}
